import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/login.vue'
import Home from '../components/home.vue'
import News from '../components/news.vue'
import Write from '../components/write.vue'
import Welcome from '../components/welcome.vue'
import Users from '../components/users.vue'
import Common from '../components/common.vue'
import Categories from '../components/categories.vue'
import Carousel from '../components/carousel.vue'
import Index from '../components/index.vue'
import Homepage from '../components/index/homepage.vue'
import IndexClass from '../components/index/indexclass.vue'
import Show from '../components/index/show.vue'
Vue.use(VueRouter)

const routes = [
  // 重定向到登陆页
  {
    path: '/',
    redirect: '/index'
  },
  {
    path: '/index',
    component: Index,
    children: [
      {
        path: '/',
        component: Homepage
      },
      {
        path: '/index/indexclass',
        component: IndexClass
      },
      {
        path: '/index/show',
        component: Show
      }
    ]
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/home',
    component: Home,
    children: [
      {
        path: '/home/',
        redirect: '/home/welcome'
      },
      {
        path: '/home/welcome',
        component: Welcome
      },
      {
        path: '/home/news',
        component: News
      },
      {
        path: '/home/write',
        component: Write
      },
      {
        path: '/home/users',
        component: Users
      },
      {
        path: '/home/common',
        component: Common
      },
      {
        path: '/home/categories',
        component: Categories
      },
      {
        path: '/home/carousel',
        component: Carousel
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪个路径跳转而来
  // next 是一个函数，表示放行
  //     next()  放行    next('/login')  强制跳转

  if (to.path === '/login') return next()
  // 获取token
  const tokenStr = window.sessionStorage.getItem('token')
  console.log(tokenStr)

  if (tokenStr == null || tokenStr === 'no') return next('/login')
  next()
})
// 多次点击导航栏不报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}
// 刷新页面回到顶部
router.afterEach((to, from, next) => {
  window.scrollTo(0, 0)
})

export default router
